package com.example.shrio;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin.entity.SysDepartment;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysUser;
import com.example.admin.service.ISysDepartmentService;
import com.example.admin.service.ISysUserService;
import com.example.shrio.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据权限
 */
@Component
public class DataScope {

    @Autowired
    private ISysUserService service;

    @Autowired
    private ISysDepartmentService deptService;

    public void dataScope(QueryWrapper wrapper) {
        SysUser sysUser = CurrentUser.getAdminUser();
        if (!sysUser.getAccount().equals("admin")) {
            List<SysRole> roles = sysUser.getRoleList();
            Set<SysUser> users = new HashSet<>();
            roles.stream().filter(info -> info.getDataScope() == 0).forEach(info -> {//自定义数据
                if (info.getDataScope() == 0) {
                    users.addAll(service.listRoleUser(info));
                }
            });
            if (roles.stream().filter(x -> x.getDataScope() == 1).anyMatch(x -> true)) {//本部門數據
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("dept_id", sysUser.getDeptId());
                users.addAll(service.list(queryWrapper));
            }
            if (roles.stream().filter(x -> x.getDataScope() == 3).anyMatch(x -> true)) {//本人数据
                users.add(sysUser);
            }
            if (roles.stream().filter(x -> x.getDataScope() == 2).anyMatch(x -> true)) {//本部门及下级部门
                List<Integer> ids = new ArrayList<>();
                deptFormate(Integer.valueOf(sysUser.getDeptId()), ids);
                ids.add(Integer.valueOf(sysUser.getDeptId()));
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.in("dept_id", ids);
                users.addAll(service.list(queryWrapper));
            }
            if (users.size() > 0) {
                wrapper.in("create_by", users.stream().map(info -> info.getId()).collect(Collectors.toList()));
            }
        }
    }


    private void deptFormate(Integer dept, List<Integer> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", dept);
        List<SysDepartment> list = deptService.list(queryWrapper);
        if (list != null && list.size() > 0) {
            list.forEach(info -> {
                if (info.getType().equals("0")) {
                    deptFormate(info.getId(), ids);
                }
                ids.add(info.getId());
            });
        }

    }


}
